import 'dart:io';
import 'dart:math';

import 'package:demo/routers/navigators.dart';
import 'package:demo/ui/display/display_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../../utils/toast.dart';
import '../../widget/app_bar.dart';
import 'home_router.dart';

class Home extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class _HomeState extends State<Home>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  static const methodChannel = MethodChannel("me.winds.flutter/method");
  static const EventChannel eventChannel =
      EventChannel("me.winds.flutter/event");

  void showToast(String msg) async {
    if (Platform.isAndroid) {
      try {
        await methodChannel.invokeMethod("showToast", {"msg": msg});
      } catch (e) {
        print(e.toString());
      }
    } else {
      Toast.show("IOS平台未定义此方法");
    }
  }

  Future<String> getSystemTime() async {
    if (Platform.isAndroid) {
      var str;
      try {
        str = await methodChannel
            .invokeMethod("getSystemTime", {"pattern": "yyyyMMdd HH:mm"});
        Toast.show("系统时间：" + str);
      } on PlatformException catch (e) {
        print(e.toString());
      }
      return str;
    } else {
      Toast.show("IOS平台未定义此方法");
    }
  }

  List<String> list = [
    '1. 调用平台方法',
    '2. 调用平台方法带返回值',
    '3. 注册平台事件',
    '4.Toast',
    '5.Navigation',
    '6.Widgets',
    '7.Dialog',
    '8.SharePerfence',
    '9.Dio',
  ];

  List<Color> _colorList = [
    Colors.black26,
    Colors.deepOrange,
    Colors.amber,
    Colors.green,
    Colors.greenAccent,
    Colors.lightBlue,
    Colors.deepOrangeAccent,
    Colors.purpleAccent,
    Colors.lightGreenAccent,
    Colors.pink,
    Colors.yellowAccent,
  ];

  bool hasNet = false;

  @override
  void initState() {
    super.initState();
    eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  }

  void _onEvent(Object obj) {
    setState(() {
      hasNet = (obj != null && obj == "网络可用");
      print("平台网络状态注册回调: " + (hasNet ? "网络可用" : "网络不可用"));
      Toast.show("平台网络状态注册回调: " + (hasNet ? "网络可用" : "网络不可用"));
    });
  }

  void _onError(Object obj) {
    setState(() {
      print("获取平台网络状态失败");
      Toast.show("获取平台网络状态失败");
    });
  }

  ScrollController _scrollerController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: "首页",
        isBack: false,
        elevation: 1,
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Colors.white,
        mini: true,
        child: Icon(
          Icons.favorite,
          color: hasNet ? Colors.red : Colors.grey,
        ),
        onPressed: () {
          //返回到顶部
          _scrollerController.animateTo(0,
              duration: Duration(milliseconds: 200), curve: Curves.ease);
        },
      ),
      body: ListView.builder(
        padding: const EdgeInsets.all(16.0),
        itemCount: list.length,
        controller: _scrollerController,
        itemBuilder: (context, i) {
          return _buildRow(context, i);
        },
      ),
    );
  }

  Widget _buildRow(BuildContext context, int index) {
    return Padding(
      padding: EdgeInsets.only(left: 2, right: 2, top: 0, bottom: 0),
      child: RaisedButton(
        child: new Text(
          list[index],
          style: TextStyle(fontSize: 16, color: Colors.white),
        ),
        color: _colorList[Random().nextInt(_colorList.length)],
        onPressed: () {
          onPressed(index);
        },
      ),
    );
  }

  void onPressed(int index) {
    switch (index) {
      case 0: //调用平台方法
        showToast("来自Flutter的问候");
        break;
      case 1: //调用平台方法带返回值
        getSystemTime();
        break;
      case 2: //Toast
        Toast.show(hasNet ? "当前网络正常" : "当前无网络");
        break;
      case 3: //Toast
        Toast.show("Flutter 内部 Toast");
        break;
      case 4: //Navigation
        Navigators.push(context, HomeRouter.navigatorPage);
        break;
      case 5: //Widgets
        Navigators.push(context, DisplayRouter.navigatorPage);
        break;
      case 6: //dialog
        Navigators.push(context, HomeRouter.dialogPage);
        break;
      case 7: //SharePreferences
        Navigators.push(context, HomeRouter.sharePreferencesPage);
        break;
      default:
        Toast.show(list[index]);
        break;
    }
  }

  @override
  bool get wantKeepAlive => true;
}
